package com.douqu.game.plantwar.main.interceptor;

import com.auth0.jwt.interfaces.Claim;
import com.douqu.game.plantwar.core.commons.AppConstant;
import com.douqu.game.plantwar.core.utils.JWTUtils;
import com.douqu.game.plantwar.core.utils.LogUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.WebFilter;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * webflux的过滤器 验证解析token
 */
@Configuration
public class MainInterceptor {

    @Bean
    public WebFilter sampleWebFilter(){
        LogUtils.info("进入过滤器");
        return (e,c)->{
            LogUtils.info(e.getRequest().getURI().getPath().indexOf("swagger-ui.html"));
            LogUtils.info("request uri" + e.getRequest().getURI());
            List<String> tokens = e.getRequest().getHeaders().get("token");
            if (tokens == null || tokens.isEmpty()){
                LogUtils.error("token is null ");
                return c.filter(e);
            }
            Map<String, Claim> paramMap = JWTUtils.verify(tokens.get(0));
            if (paramMap == null){
                LogUtils.error("paramMap is null");
                return c.filter(e);
            }
            Long roleId = paramMap.get(AppConstant.ROLE_ID_PREX).asLong();
            String account = paramMap.get(AppConstant.ACCOUNT).asString();
            e.getAttributes().put(AppConstant.ROLE_ID_PREX,roleId);
            e.getAttributes().put(AppConstant.ACCOUNT,account);
            return c.filter(e);
        };
    }
}
